<template>
    <div id="background">
        <el-container style="height:100%;" direction="vertical">
            <el-header v-show="!shiPinShow" id="spHead" style="position:fixed;top:0px;width:100%;z-index:10000">
                <el-row type="flex" style="height:80%;display:flex;align-items: flex-end">
                    <el-col :xs="2" :sm="2" :md="2" :offset="1" class="imgCol">
                        <img v-bind:src="backIcon" class="backSize" @click="back" />
                    </el-col>
                </el-row>
            </el-header>
            <el-main id="spMain">
                <!-- <div style="width:100%;" id="spBoFang">
                        <video-player class="video-player vjs-custom-skin" 
                            ref="videoPlayer" 
                            :playsinline="true" 
                            :options="playerOptions" 
                            @play="onPlayerPlay($event)"
                            @pause="onPlayerPause($event)"
                        >
                        </video-player>
                </div> -->
                
                    <div  id="mse" class="mse"></div>
                   
                <van-tabs v-model="activeName" line-height="1px" color="#53cdf5" id="spDaoHang" @click="onClick" sticky>
                    <van-tab title="简介" name="jj"></van-tab>
                    <van-tab title="目录" name="ml"></van-tab>
                    <van-tab title="评论" name="pl"></van-tab>
                </van-tabs>
                <el-scrollbar id="dhContent">
                    <div v-if="flag=='ml'" >
                            <el-collapse  @change="handleChange" style="padding-left:20px;padding-right:20px;"  v-model="activeNames">
                                <el-collapse-item v-for="(value,key) in keChengs" :key="key" :name="value.no">
                                    <div slot="title">{{value.chapterName}}</div>
                                    <div v-for="(value,key) in value.chapterContent.classNameAndIdAndNo" :key="key">
                                        <div class="keShi" v-if="isPlay==value.id" style="background-color:#97e5fa;">
                                        <el-row style="margin-left:5px;margin-top:5px;margin-bottom:5px;color:#fff;position:relative;">
                                            <el-col class="leftContent" >
                                                <el-row class="spRow1 noHuanHang">
                                                    <span >
                                                        {{'第'+value.No+'课时:'+' '+value.name}}
                                                    </span>
                                                </el-row>
                                                <el-row class="spRow2" style="font-size:12px;">
                                                    <span>
                                                        <img src="../../assets/img/peiXun/shiPing/shiChang.png" style="width:12px;height:12px;">
                                                        {{shiChang}}
                                                    </span>
                                                    <span>
                                                        <img src="../../assets/img/peiXun/shiPing/kanGuo.png" style="width:14px;height:10px;">
                                                        {{kanGuo}}
                                                    </span>
                                                    <span>
                                                        <img src="../../assets/img/peiXun/shiPing/yiKan.png" style="width:12px;height:12px;">
                                                    </span>
                                                </el-row>
                                            </el-col>
                                            <el-col class="rightContent1 imgCol"> 
                                                <span class="scandfxPosition">
                                                    <span style="width:30px;">
                                                    <img src="../../assets/img/peiXun/shiPing/shouCang.png" style="width:12px;height:12px;">
                                                    </span>
                                                    <span style="margin:5px;">|</span>
                                                    <span style="width:30px;" @click="getFenXiangLianJie">
                                                    <img src="../../assets/img/peiXun/shiPing/fenXiang.png" style="width:12px;height:12px;">
                                                    </span>
                                                </span>
                                            </el-col>
                                        </el-row>
                                        </div>
                                        <div class="keShi"  v-else style="background-color:#dfdfdf;" @click="boFang(value.id)">
                                        <el-row style="margin:5px;color:#fff;position:relative">
                                            <el-col class="leftContent" >
                                                <el-row class="spRow1 noHuanHang">
                                                    <span>
                                                        {{'第'+value.No+'课时:'+' '+value.name}}
                                                    </span>
                                                </el-row>
                                                <el-row class="spRow2" style="font-size:12px;">
                                                    <span>
                                                        <img src="../../assets/img/peiXun/shiPing/shiChang.png" style="width:12px;height:12px;">
                                                        {{shiChang}}
                                                    </span>
                                                    <span>
                                                        <img src="../../assets/img/peiXun/shiPing/kanGuo.png" style="width:14px;height:10px;">
                                                        {{kanGuo}}
                                                    </span>
                                                    <span>
                                                        <img src="../../assets/img/peiXun/shiPing/yiKan.png" style="width:12px;height:12px;">
                                                    </span>
                                                </el-row>
                                            </el-col>
                                            <el-col class="rightContent imgCol"> 
                                                <span class="shiKanPosition" >
                                                <img src="../../assets/img/peiXun/shiPing/shiKan.png" style="width:12px;height:12px;">
                                                试看
                                                </span>
                                            </el-col>
                                        </el-row>
                                        </div>
                                    </div>
                                </el-collapse-item>
                            </el-collapse>
                    </div>
                    <div v-else-if="flag=='jj'">
                        <div class="jjContent">
                            <div class="jjTitle">
                                1.课程介绍
                            </div>
                            <div class="line"></div>
                            <div class="neiRong">
                                {{kcjs}}
                            </div>
                            <div class="line"></div>
                            <div class="jjTitle">
                                2.讲师介绍
                            </div>
                            <div class="line"></div>
                            <div class="neiRong">
                                {{jsjs}}
                            </div>
                            <div class="line"></div>
                            <div class="jjTitle">
                                3.适合人群
                            </div>
                            <div class="line"></div>
                            <div class="neiRong">
                                {{mxrq}}
                            </div>
                            <div class="line"></div>
                            <div class="jjTitle">
                                4.面向岗位
                            </div>
                            <div class="line"></div>
                            <div class="neiRong">
                                {{mxgw}}
                            </div>
                            <div class="line"></div>
                        </div>
                    </div>
                    <div v-else>
                            <div v-for="(value,key) in pingLun" :key="key">
                                <div class="plContent">
                                    <span style="margin-right:10px;margin-left:8px;">
                                        {{value.username}}
                                    </span>
                                    <span>
                                        {{value.text}}
                                    </span>
                                </div>
                            </div>
                    </div>
                     <div style="height:40px;"></div>
                </el-scrollbar>
            </el-main>
            <div style="backgroundColor:#ffffff">
                <el-row type="flex" :class="whichPosition?'shiPinFootPosition':'imgCol'"> 
                    <button class="spbtn" style="width: 80%;">
                       <span class="spBtnWords" style="margin-right:5px;">{{'¥'+price}}</span>
                       <span class="spBtnWords" style="margin-right:10px;">|</span>
                       <span class="spBtnWords" @click="payShiPin()">立即购买</span>
                    </button>
                </el-row>
         </div>
        </el-container>
    </div>    
</template>

<script>
import Player from 'xgplayer';   //引入西瓜视频组件
import { Collapse, CollapseItem } from 'vant';

import cover from '../../assets/img/peiXun/shiPing/cover.jpg';
import video from '../../assets/video/v1.mp4';
// import { videoPlayer } from 'vue-video-player';
import { version } from 'punycode';
import backIcon from '../../assets/img/mine/back.png'
export default {
    watch:{
        showHeight(val){
            //console.log("shoHeight"+this.showHeight);
            this.whichFoot();
        },
    },
    data(){
        return{
            //视频URL
            videoUrl:'',

            whichPosition:true,
            //实时屏幕高度
            showHeight:document.documentElement.clientHeight,
            height:document.documentElement.clientHeight,
            shiPinShow:false,
            backIcon:backIcon,
            shiPingId:1,
            fenXiangLianJie:'',
            isPlay:1,
            // playerOptions:{
            //     playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度 
            //     autoplay: false, //如果true,浏览器准备好时开始回放。 
            //     muted: false, // 默认情况下将会消除任何音频。 
            //     loop: false, // 导致视频一结束就重新开始。 
            //     preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持） 
            //     language: 'zh-CN', 
            //     aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"） 
            //     fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。 
            //     sources: [{ 
            //         type: "video/mp4", 
            //         src: video
            //     }], 
            //     // poster: cover, 
            //     width: document.documentElement.clientWidth, 
            //     notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。 
            //     controlBar: { 
            //         volumeControl: false,//声音播放键
            //         timeDivider: false, 
            //         durationDisplay: false, 
            //         remainingTimeDisplay: false, 
            //         fullscreenToggle: true //全屏按钮
            //     }
            // },
            activeName:'jj',
            flag:'jj',
            activeNames: [1],
            keChengs:[],
            shiChang:'5分45秒',
            kanGuo:'3145',
            jsjs:'',
            kcjs:'',
            mxrq:'',
            mxgw:'',
            //课程ID
            id:'',
            price:'',
            pageNo:'1',
            pageSize:'8',
            pingLun:[],
            videoUrl:'',
            // normalHeight:document.documentElement.clientHeight,
            //绑定支付订单
            order:'',
            //绑定支付通道
            pays:{"":""},
        }
    },
    created(){
      this.plusReady();
    },
     mounted(){
         // window.onresize监听页面高度的变化
        const that = this;
        window.onresize = () => {
            return (() => {
                window.screenHeight=document.documentElement.clientHeight;
               that.showHeight=window.screenHeight;
            })()
         }

        var courseId=this.$route.query.courseId;
        this.id=courseId;

        var normalHeight=sessionStorage.getItem('normalHeight');
        var bg = document.getElementById("background");
        console.log("height:"+normalHeight);
        bg.style.height = normalHeight+"px";
        bg.style.backgroundColor = "#FFFFFF"
        bg.style.margin = "0px";
        
        var head=document.getElementById("spHead");
        var headHeight=normalHeight/30 *4 ;
        console.log("headHeight:"+headHeight);
        head.style.height=headHeight+"px";

        var boFang=document.getElementById("mse");
        var boFangHeight=normalHeight/30 *8 ;
        console.log("boFangHeight:"+boFangHeight);
        boFang.style.height=boFangHeight+"px";

        var daohang=document.getElementById("spDaoHang");
        var daohangHeight=normalHeight/30 *0.5 ;
        console.log("daohangHeight:"+daohangHeight);
        daohang.style.height=daohangHeight+"px";

        // var dhNeiRong=document.getElementById("dhContent");
        // var dhNeiRongHeight=normalHeight/30 *17.5 ;
        // console.log("dhNeiRongHeight:"+dhNeiRongHeight);
        // dhNeiRong.style.height=dhNeiRongHeight+"px";

        // var foot=document.getElementById("spFoot");
        // var footHeight=this.normalHeight/30 *2.5;
        // foot.style.height=footHeight+"px";

        this.getIntroduction();
        this.getPrice();
        this.getkeChengs();
        this.getShiPing();
        this.getPinglun();



    },
    methods: { 
        //播放器初始化
        playerInit(){   //4、设置视频配置(注意：playerInit应放在异步函数里或mounted之后，不可在created里直接加载，否则不生效)
                let player = new Player({   //初始化player实例对象
                    id:'mse',
                    url: this.videoUrl,   //视频链接
                    ignores: ['progress'],
                    fluid: true,   //流式布局
                    whitelist: ['iPhone','Android'],   //白名单
                    'x5-video-orientation': 'landscape'
                });
                player.on('play',function(){    //注册并监听播放事件
                    this.shiPinShow=true;
                    console.log('播放了'+this.shiPinShow)
                    
                })
                player.on('pause',function(){   //注册并监听暂停事件
                    this.shiPinShow=false;
                    console.log('暂停了'+this.shiPinShow)
                })
        },
        whichFoot(){
            if(this.showHeight<this.height){
                //console.log("foot not fixed");
                this.whichPosition=false;
            }else{
                //console.log("foot fixed");
                this.whichPosition=true;
            }
        },

        boFang(id){
            this.isPlay=id;
            this.shiPingId=id;
            console.log('这里是视频ID'+this.shiPingId);
            this.getShiPing();
        },
        getShiPing(){
            var URL=this.IP.IP+'/course/video';
            this.$ajax({
                    method:'get',
                    url:URL,
                    params: {
                        id:this.shiPingId,
                    },
                }).then(response =>{
                var code=response.data.code;
                if(code==0){
                //     this.playerOptions.sources[0].type='video/mp4';
                // this.playerOptions.sources[0].src=response.data.data;
                // console.log('视频源：'+this.playerOptions.sources[0].src);
                this.videoUrl=response.data.data;
                console.log('视频源：'+this.videoUrl);
                this.playerInit();//为什么在这里调用playerInit函数而不在mounted生命周期中调用？因为接口请求是异步的，在mounted中接口调用还未返回数据，故playerConfig中的数据仍然为空。而视频组件依赖于playerConfig中的数据
                }else{
                    Toast(response.data.msg);
                }   
                }).catch(error => {
                console.log('获取视频失败');
                });
        },
        getFenXiangLianJie(){
            var URL=this.IP.IP+'/course/videoLink';
            this.$ajax({
                    method:'get',
                    url:URL,
                    params: {
                        id:this.shiPingId,
                    },
                }).then(response =>{
                var code=response.data.code;
                if(code==0){
                this.fenXiangLianJie=response.data.data;
                console.log('视频链接：'+this.fenXiangLianJie);
                }else{
                    Toast(response.data.msg);
                }   
                }).catch(error => {
                console.log('获取链接失败');
                });
        },
        getPinglun(){
            var URL=this.IP.IP+'/course/commentReturn';
            this.$ajax({
                    method:'get',
                    url:URL,
                    params: {
                        id:this.id,
                        pageNo:this.pageNo,
                        pageSize:this.pageSize,
                    },
                }).then(response =>{
                this.pingLun=response.data.data.info;
                console.log(response);
                }).catch(error => {
                console.log('评论获取失败');
                });
        },
        getkeChengs(){
            var URL=this.IP.IP+'/course/catalogue';
            this.$ajax({
                    method:'get',
                    url:URL,
                    params: {
                        id:this.id,
                    },
                }).then(response =>{
                this.keChengs=response.data.data;
                this.shiPingId=this.keChengs[0].chapterContent.classNameAndIdAndNo[0].id;
                console.log('这里是刚进来时的视频id'+this.shiPingId);
                this.isPlay=this.shiPingId;
                console.log('这里是课程概览'+this.id);
                this.getShiPing();
                }).catch(error => {
                console.log('课程概览获取失败');
                });
        },
        getPrice(){
            var URL=this.IP.IP+'/course/price';
            this.$ajax({
                    method:'get',
                    url:URL,
                    params: {
                        id:this.id,
                    },
                }).then(response =>{
                this.price=response.data.data;
                }).catch(error => {
                console.log('价格获取失败');
                });
        },
        getIntroduction(){
            var URL=this.IP.IP+'/course/introduction';
            this.$ajax({
                    method:'get',
                    url:URL,
                    params: {
                        id:this.id,
                    },
                }).then(response =>{
                this.kcjs=response.data.data.content.courseIntroduction;
                this.jsjs=response.data.data.content.teacherIntroduction;
                this.mxrq=response.data.data.content.forCrowd;
                this.mxgw=response.data.data.content.forPost;
                }).catch(error => {
                console.log('简介获取失败');
                });
        },
        onClick(name, title) {
            this.flag=name;
        },
        handleChange(val) {
            console.log(val);
        },
        // fullScreen() { 
        //     const player = this.$refs.videoPlayer.player 
        //     player.requestFullscreen()//调用全屏api方法 
        //     player.isFullscreen(true) 
        //     player.play() 
        // }, 
        // onPlayerPlay(player) { 
        //     // player.play() 
        //     this.shiPinShow=true;
        //     console.log("play");
        // }, 
        // onPlayerPause(player) { 
        //     // alert("pause");
        //     this.shiPinShow=false;
        //     console.log("pause");
        // }, 
        back(){
            console.log("back:");
            this.$router.go(-1);
        },
        payShiPin(){
            var w=null;
            var that=this;
             //var url='http://demo.dcloud.net.cn/payment/?payid=alipay';
            var url="https://openapi.alipay.com/gateway.do"
            // 支付
            var appid=plus.runtime.appid;
	          if(navigator.userAgent.indexOf('StreamApp')>=0){
		          appid='Stream';
	          }
	        //   url+='&appid='+appid+'&total=1'
	          // url+='&total=1'
            w=plus.nativeUI.showWaiting();
           var xhr=new XMLHttpRequest();
            this.getRes(w);
            xhr.onreadystatechange=function(){
		          switch(xhr.readyState){
			          case 4:
			            w.close();w=null;
			            if(xhr.status==200){
				            console.log('----- 请求订单成功 -----');
				            //console.log(xhr.responseText);
                           // var order=xhr.responseText;
                           console.log(that.order);
				            plus.payment.request(that.pays['alipay'],that.order,function(result){
					          console.log('----- 支付成功 -----');
					          console.log(JSON.stringify(result));
					          plus.nativeUI.alert('支付成功！',function(){
						            back();
					            },'支付');
				            },function(e){
					            console.log('----- 支付失败 -----');
					            console.log('['+e.code+']：'+e.message);
					            plus.nativeUI.alert('支付失败', null, '支付失败：'+e.code);
				            });
			            }else{
				            console.log('----- 请求订单失败 -----');
				            console.log( xhr.status );
				            plus.nativeUI.alert('获取订单信息失败！', null, '捐赠');
			            }
		              break;
			          default:
			            break;
		          }
            }
    	      xhr.open('GET',url);
	          console.log('请求支付订单：'+url);
	          xhr.send();
        },  
        plusReady() {
            var that = this;
            console.log("输出pays:");
            console.log(that.pays);
            // var pays={};
            // 获取支付通道
            plus.payment.getChannels(function (channels) {
            for (var i in channels) {
                var channel = channels[i];
                if (channel.id == 'qhpay' || channel.id == 'qihoo') { // 过滤掉不支持的支付通道：暂不支持360相关支付
                    continue;
                }
                console.log(channel.id);
                console.log(channel);
                that.pays[channel.id] = channel;
            }
            }, function (e) {
                console.log('获取支付通道失败：'+e.message);
            });
        },
         //得到订单号
        getRes(w){
             var URL=this.IP.IP+'/pay/params';
            console.log(URL);
            console.log(this.trainClassTimeId);

            this.axios({
               method:'get',
               url:URL,
               params:{
                 goodId:this.id,
                 goodType:'COURSE'
               }
           }).then(response=>{
               var code=0;
               code=response.data.code;
               if(code==0){
                    this.order=response.data.data;
                    console.log("order:");
                    console.log(this.order);
               }else{
                  w.close();
                   Toast(response.data.msg);
               }   
           }).catch(error=>{
               console.log(error);
           })
        },

    },
    // components: {
    //     videoPlayer
    // },
    // computed: { 
    //     player() { 
    //         return this.$refs.videoPlayer.player 
    //     }
    // } 

}
</script>

<style>
.noHuanHang{
    white-space: nowrap;
    overflow: hidden;
}
.shiPinFootPosition{
    position:fixed;
    bottom:10px;
    width:100%;
    display:flex;
    align-items:center;
    justify-content:center
}
/* .van-collapse-item__content{
    padding-left: 15px;
    padding-right: 15px;
} */
.imgCol{
    display:flex;
    align-items:center;
    justify-content:center
}
.rightContent1{
    font-size:12px;
    text-align:center;
    height:100%;
    position: absolute;
    right:0;
    width:30%;
    background-color:#eebf6a;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    float: right;
}
.scandfxPosition{
    position: absolute;
    top:30%;
}
.el-collapse-item__header{
    color: #707070;
}
#spFoot{
    padding-left: 15px;
    padding-right: 15px;
}
#spMain{
    padding: 0;
}
#spBoFang{
    padding:0;
}
#spHead{
    background-color: rgb(255,255,255,0);
}
.rightContent{
    position: absolute;
    width:30%;
    height:100%;
    right:0;
}
.leftContent{
    width:70%;
}
.keShi{
    border-radius: 4px;
}
.neiRong{
    font-size: 12px;
    color: #707070;
    margin-top: 10px;
    margin-bottom: 10px;
    margin-left:10px;
    width: 100%;
    
}
.jjContent{
    padding-left: 20px;
    padding-right: 20px;
}
.jjTitle{
    font-size: 16px;
    color: #707070;
    margin-bottom: 10px;
    margin-top: 10px;
}
.line{
    width: 100%;
    height: 1px;
    background-color: #F0F0F0;
}
.plContent{
    background-color:  #dfdfdf;
    color: #707070;
    border-radius: 4px;
    margin-left:20px;
    margin-right:20px;
    margin-top:10px;
}
.spBtnWords{
    text-align: center;
    font-size: 16px;
    font-weight: 400;
    color: #FFFFFF;
}
.spbtn{
    /* line-height: 40px; */
    height: 40px;
    font-size: 1.125em;
    width: 80%;
    background-color: #53cdf5;
    border-style: none;
    outline: none;
    -webkit-border-radius: 25px;
    -moz-border-radius: 25px;
    -ms-border-radius: 25px;
    -o-border-radius: 25px;
    border-radius: 25px;
}
/* .video-js .vjs-big-play-button {  
    border-radius: 50%;
    width: 68px;
    z-index: 100; 
    background-color: #131212; 
    border: solid 1px #979797; 
} */
.backSize{
    height: 26px;
}
.titleSize{
    font-size:1.125em;
    color:#ffffff
}
@media screen and (max-height: 600px){
  .backSize{
      height: 22px;
  }
  .titleSize{
      font-size: 1em;
  }
}
</style>
